import getConfig from "../utils/getConfig";
import initDbPool from '../db/initDbPool';
import initRouter from "../middlewares/routerHandler";
import fs from 'fs';
import path from "path";
import { Config } from "../types/global";
import MyError from "./myError";
import logger from "./logger";
const initConfig = async () => {
    try {
        const uploadsHandler = (uploadsPath: string) => {
            fs.stat(path.resolve(uploadsPath), (err, stat: fs.Stats) => {
                if (err) {
                    fs.mkdir(uploadsPath, { recursive: true }, (e) => {
                        if (e) {
                            throw new MyError(e.message)
                        }
                    });
                }
            })
        }
        const properties = await getConfig();
        const envConfig = new Map<string, any>();
        for (const key in properties) {
            envConfig.set(key, properties[key]?.[process.env.NODE_ENV] || properties[key]);
        }
        global.config = envConfig as Config;
        void await uploadsHandler(envConfig.get('uploadsPath')?.prod || envConfig.get('uploadsPath'))
        void await initDbPool();
        void await initRouter();
    } catch (error) {
        throw new MyError(`初始化配置失败:${error}`)
    }
}
export default initConfig;